<template>
  <BasicDrawer 
    v-bind="$attrs" @register="registerDrawer" 
    :title="getTitle" width="650px" 
    @ok="handleSubmit" show-footer
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { defineComponent, ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "../data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { updateUser, getUserDetails, getUserDeptList } from "../api"
  import * as tenantUserApi from "/@/api/iam/tenantUser.ts"
  import { isString, isArray } from "/@/utils/is"

  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  const deptOptions = ref([])

  const wrapperCol: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 24, // ≥992px
    xl: 24, // ≥1200px
    xxl: 24, // ≥1600px
  }

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 80,
    baseColProps: { lg: 24, md: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      setDrawerProps({ loading: true })
      try {
        rowId.value = data.record.id

        //查角色/赋值/try catch 处理，不然编辑有问题
        try {
          data.record = await getUserDetails({ userId: data.record.id })
          const userRoles = data.record.roleList
          if (userRoles && userRoles.length > 0) {
            data.record.roleIds = userRoles.map((e) => e.id)
          }

          const userDept = data.record.deptList
          if (userDept && userDept.length > 0) {
            let selectDeptKeys = Array.from(userDept, ({ key }) => key)
            data.record.deptIds = selectDeptKeys.join(",")
            deptOptions.value = userDept.map((item) => {
              return { label: item.title, value: item.key }
            })
          }
        } catch (error) {}
      } finally {
        setDrawerProps({ loading: false })
      }
    }
    setFieldsValue({ ...data.record })

    //编辑时隐藏密码/角色列表隐藏角色信息/我的部门时隐藏所属部门
    updateSchema([
      {
        field: "deptIds",
        componentProps: ({ formActionType, formModel }) => {
          return {
            sync: false,
            checkStrictly: true,
            defaultExpandLevel: 3,
            options: deptOptions.value,
            // 不允许搜索
            showSearch: false,
            onSelect: (options, values) => {
              const { updateSchema } = formActionType
              console.log("values: ", values)
            },
          }
        },
      },
      {
        field: "selectedDepts",
        show: !data?.departDisabled,
      },
    ])

    setProps({ disabled: !showFooter })
  })

  const getTitle = computed(() => "新增用户")

  async function handleSubmit() {
    try {
      let values = await validate()
      const reqParams = { ...values }
      if (isString(reqParams.deptIds)) {
        reqParams.deptIds = reqParams.deptIds.split(',')
      }

      if (isString(reqParams.postIds)) {
        reqParams.postIds = reqParams.postIds.split(',')
      }

      if (isString(reqParams.roleIds)) {
        reqParams.roleIds = reqParams.roleIds.split(',')
      }
      setDrawerProps({ confirmLoading: true })
      await tenantUserApi.saveUser(reqParams)
      closeDrawer()
      emit("success", { values: { ...values } })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
